package security.core;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LocalAuthenticationInterceptor extends HandlerInterceptorAdapter {
	
	private static Log LOG = LogFactory.getLog(LocalAuthenticationInterceptor.class);
	
	@Autowired
	private AuthenticationManager authenticationManager;
	
	@Override
	public boolean preHandle(HttpServletRequest requst, HttpServletResponse response, Object handler) throws Exception {
		//AnonymousAuthenticationFilter anonymousAuthenticationFilter;
		//If the request already filtered by UsernamePasswordAuthenticationFilter, then authentication will be UsernamePasswordAuthenticationToken
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication != null) {
			String username= authentication.getName();
			String password = Objects.toString(authentication.getCredentials(), "");
			LOG.info("username: " +  username);
			LOG.info("password: " +  password);
			if(username != null) {
				LOG.info(authentication.isAuthenticated());
				if(this.authenticationManager != null) {
					this.authenticationManager.authenticate(authentication);
					LOG.info("authenticationManager.authenticate result : " + authentication.isAuthenticated());
					SecurityContextHolder.getContext().setAuthentication(authentication);
				}
			}
		}
		return true;
	}
	
}
